package net.wicp.tams.commons.thread.event;

import java.util.HashMap;
import java.util.Map;

import com.google.common.eventbus.AsyncEventBus;

import net.wicp.tams.commons.constant.ObjectElement;
import net.wicp.tams.commons.thread.ThreadPool;

/****
 * 异步调用工具
 * 
 * @author zhoujunhui
 *
 */
@SuppressWarnings("rawtypes")
public class EnventBus {
	private AsyncEventBus eventBus = null;
	private static Object lockobj = new Object();
	private static volatile EnventBus INSTANCE;

	private EnventBus() {
		eventBus = new AsyncEventBus("enventBusUtil", ThreadPool.getDefaultPool());
		eventBus.register(new EventListener());
	}

	/***
	 * 双重检查
	 * 
	 * @return
	 */
	public static final EnventBus getInstance() {
		if (INSTANCE == null) {
			synchronized (lockobj) {
				if (INSTANCE == null) {
					INSTANCE = new EnventBus();
				}
			}
		}
		return INSTANCE;
	}

	public void invokeAsyn(Object bean, String methodName, Object[] args, Class[] clazzs) {
		Event event = new Event(bean, methodName, args, clazzs);
		eventBus.post(event);
	}

	public void invokeAsyn(Object bean, String methodName, Object... args) {
		this.invokeAsyn(bean, methodName, args, null);
	}

	/****
	 * 异步调用静态方法
	 * 
	 * @param className
	 *            类名
	 * @param methodName
	 *            方法名
	 * @param params
	 *            参数
	 */
	public void listenStatic(String className, String methodName, Object... params) {
		Map<ObjectElement, Object> inputobj = new HashMap<>();
		inputobj.put(ObjectElement.className, className);
		inputobj.put(ObjectElement.methodName, methodName);
		inputobj.put(ObjectElement.params, params);
		eventBus.post(inputobj);
	}

}
